<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>react-to-wc</title>
  </head>
  <body>
    <!-- <script src="https://unpkg.com/react@18.3.1/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.production.min.js"></script> -->
    <script src="libs/react.production.min.js"></script>
    <script src="libs/react-dom.production.min.js"></script>
    <script src="dist/react-web-components.umd.js"></script>
    <div>
      <button id="add">添加HelloWorld</button>
      <button id="modify">更改第一个helloworld的msg</button>
      <button id="remove">删除第一个HelloWorld</button>
    </div>
    <hello-world msg="React">
      <div style="color: chocolate; font-weight: bold">外部HTML内容</div>
    </hello-world>
    <hello-web-component></hello-web-component>
    <script>
    const eventHandler = (e) => {
        alert(e.detail.msg);
    };
    ReactWebComponents.registerWebComponents();

    const helloWorld = document.querySelector("hello-world");
      // 监听hello-world组件的广播的事件
    helloWorld.addEventListener("myEvent", eventHandler);


      // 添加
    const addButton = document.querySelector("#add");
    addButton.addEventListener("click", () => {
        const element = document.createElement("hello-world");
        const helloWorldNum = document.querySelectorAll("hello-world").length;
        element.setAttribute("msg", `React${helloWorldNum+1}`);
        document.body.appendChild(element);

        element.addEventListener("myEvent", eventHandler);
    });

    // 修改
    const modifyButton = document.querySelector("#modify");
    modifyButton.addEventListener("click", () => {
        const element = document.querySelector("hello-world");
        element.setAttribute("msg", "World");
    });

    // 删除
    const removeButton = document.querySelector("#remove");
    removeButton.addEventListener("click", () => {
        const element = document.querySelector("hello-world");
        element.remove();
        // 移除监听
        element.removeEventListener("myEvent", eventHandler);
    });
    </script>
  </body>
</html>
